package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EditPasswordDTO;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

/**
 * 员工业务层实现类
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    private final EmployeeMapper employeeMapper;

    @Autowired
    public EmployeeServiceImpl(EmployeeMapper employeeMapper) {
        this.employeeMapper = employeeMapper;
    }


    /**
     * 添加员工
     *
     * @param employeeDTO 员工信息
     */
    public void addEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        // 将DTO中的数据拷贝到实体对象中
        BeanUtils.copyProperties(employeeDTO, employee);
        // 添加DTO中没有的属性
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        // 调用mapper的insert方法
        employeeMapper.insert(employee);
    }

    /**
     * 分页查询员工
     *
     * @param employeePageQueryDTO 查询条件
     * @return 分页查询结果
     */
    @Override
    public PageResult<Employee> pageQueryEmployee(EmployeePageQueryDTO employeePageQueryDTO) {
        Page<Employee> empPage = PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        Page<Employee> page = employeeMapper.pageQueryEmployee(employeePageQueryDTO);
        empPage.close(); // 关闭分页查询
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    /**
     * 员工登录
     *
     * @param employeeLoginDTO 登录信息
     * @return 员工实体
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 进行md5加密，然后再进行比对
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (! md5Password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 更新员工状态
     *
     * @param id     员工id
     * @param status 员工状态
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        Employee employee = Employee.builder().id(id).status(status).build();

        employeeMapper.updateEmployee(employee);
    }

    /**
     * 更新员工
     *
     * @param employeeDTO 员工信息
     */
    @Override
    public void updateEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employeeMapper.updateEmployee(employee);
    }

    /**
     * 根据员工id查询员工
     *
     * @param id 员工id
     * @return 员工信息
     */
    @Override
    public Employee selectEmployeeById(Long id) {
        return employeeMapper.selectEmployeeById(id);
    }

    /**
     * 修改密码
     *
     * @param editPasswordDTO 修改密码信息
     */
    @Override
    public void editPassword(EditPasswordDTO editPasswordDTO) {
        if (editPasswordDTO.getOldPassword() != null
                && editPasswordDTO.getNewPassword() != null
                && editPasswordDTO.getOldPassword().equals(editPasswordDTO.getNewPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_NOT_SAME);
        }

        // 获取当前登录的员工信息
        Long empId = BaseContext.getCurrentId();
        Employee employee = employeeMapper.selectEmployeeById(empId);
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        String oldPassword = DigestUtils.md5DigestAsHex(editPasswordDTO.getOldPassword().getBytes());
        if (! oldPassword.equals(employee.getPassword())) {
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_ERROR);
        }

        String newPassword = DigestUtils.md5DigestAsHex(editPasswordDTO.getNewPassword().getBytes());
        employee.setPassword(newPassword);
        employeeMapper.updateEmployee(employee);
    }
}
